// pages/pay/Pay.js
var Zan = require('../../dist/index.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();

var start = 0;

Page(Object.assign({}, Zan.TopTips, Zan.Switch, {

  /**
   * 页面的初始数据
   */
  data: {
    userName: null,
    deliverAddress: null,
    userPhone: null,
    liuyan: '',
    products: [],
    shoppingCartIds: [],
    selectCouponed: true,
    coupon: null,
    content: "",
    allPrice: 0, // 总价
    couponPrice: 0, // 优惠券可低多少钱
    integralPrice: 0, // 积分可低多少钱
    discountPrice: 0, // 实付金额
    zhekou: 0,
    orderId: null,
    orderNO: null,
    orderDesc: null,
    canPay: true,
    againPay: 0,
    isMax: false,
    distributorId: "",
    useCoupon: false, // 是否使用优惠券
    useIntegral: false, // 是否使用积分
    integralRule: null,
    integral: 0,
    animationData: {},
    couponSwitch: {
      checked: false
    },
    integralSwitch: {
      checked: false
    },
    jifendikou: 0,
    mode1: 0,
    mode2: 1,
    radiochecked: 0,
    shop_details: {},
    date: 0,
    dateStr: '自提时间',
    formId: '',
    day: [],
    count: 1,
    multiIndex: [0, 0],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    // 注册列表刷新事件
    WxNotificationCenter.addNotification("RefreshNotification", this.refreshNotification, this)

    // var mode2 = options.mode2
    // if (mode2 !== undefined) {
    //   if (mode2 == 0) {
    //     this.setData({
    //       mode1: 1,
    //       mode2: 0,
    //       radiochecked: 1,
    //       shop_details: wx.getStorageSync('shop_details'),
    //       date: options.deliverytime
    //     })
    //   } else {
    //     this.setData({
    //       mode1: 0,
    //       mode2: 1
    //     })
    //   }
    // }

    try {
      var value = wx.getStorageSync('products')
      getCount(this, value);
      if (value) {
        // Do something with return value
        this.setData({
          products: value
        })
      }
    } catch (e) {
      // Do something when catch error
    }
    if (options.shoppingCartIds) {
      this.setData({
        shoppingCartIds: JSON.parse(options.shoppingCartIds),
      })
    }
    if (options.orderNO) {
      this.setData({
        orderId: options.orderId,
        orderNO: options.orderNO,
        orderDesc: options.orderDesc,
        againPay: options.againPay
      })
    }
    if (options.storeId) {
      this.setData({
        mode1: 1,
        mode2: 0,
        radiochecked: 1
      })
    }

    var total = getTotal(this, this.data.products);
    this.setData({
      allPrice: total,
      discountPrice: total
    })

    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        distributorId: app.globalData.userAndTenantInfo.chiefUserId,
        integral: app.globalData.userAndTenantInfo.integral
      })
      network._post_json(this, api.getUserInfo, { appId: app.globalData.appId, openId: app.globalData.openId }, userAndTenantInfoSuccess);
    } else {
      app.userAndTenantInfoCallback = res => {
        this.setData({
          distributorId: res.chiefUserId,
          integral: res.integral
        })
        network._post_json(this, api.getUserInfo, { appId: app.globalData.appId, openId: app.globalData.openId }, userAndTenantInfoSuccess);
      }
    }

    let week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六', '周日', '周一'];
    let index = new Date().getDay();
    let day = [['今天（' + week[index] + '）', '明天（' + week[index + 1] + '）', '后天（' + week[index + 2] + '）'], ['上午', '下午', '晚上']];

    this.setData({
      day: day,
      date: new Date().getTime(),
      dateLink: 0,
      dateStr: day[0][0] + day[1][0]
    })

    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    network._post_json(this, api.integralRule, {}, integralRuleSuccess);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value,
      date: new Date().getTime() + e.detail.value[0] * 24 * 60 * 60 * 1000,
      dateLink: e.detail.value[1],
      dateStr: this.data.day[0][e.detail.value[0]] + this.data.day[1][e.detail.value[1]]
    })
  },

  bindTextArea: function (e) {
    this.setData({
      content: e.detail.value
    })
  },

  /**
   * 选择地址
   */
  chooseAddress: function (e) {
    var that = this;
    wx.getSetting({
      success: function (res) {
        if (res) {
          if (!res.authSetting["scope.address"]) {
            wx.openSetting({
              success: function (res) {
                wx.chooseAddress({
                  success: function (res) {
                    that.setData({
                      userName: res.userName,
                      deliverAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
                      userPhone: res.telNumber
                    })
                  }
                })
              }
            });
          } else {
            wx.chooseAddress({
              success: function (res) {
                that.setData({
                  userName: res.userName,
                  deliverAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
                  userPhone: res.telNumber
                })
              }
            })
          }
        }
      }
    })
  },

  /**
   * 选择优惠券
   */
  chooseCoupon: function (e) {
    var productId = [];
    for (var i = 0; i < this.data.products.length; i++) {
      productId.push(this.data.products[i].id)
    }
    wx.navigateTo({
      url: '/pages/myself/coupon/ChooseCoupon?price=' + this.data.allPrice,
    })
  },

  /**
   * 获取选择的优惠券
   */
  getCoupon: function (coupon) {
    var total = getTotal(this, this.data.products);
    var couponPrice = utils.concessionalRate(this, total, coupon);
    var discountPrice = total - couponPrice;
    // 获到选获取后的价格
    if (couponPrice > 0) {
      this.setData({
        coupon: coupon
      })
    }
    this.setData({
      couponPrice: couponPrice,
      discountPrice: getPaidPrice(this, this.data.allPrice, couponPrice, 0)
      // discountPrice: getPaidPrice(this, this.data.allPrice, couponPrice, this.data.integralPrice)
    })

  },

  handleZanSwitchChange: function (e) {
    var componentId = e.componentId;
    var checked = e.checked;

    // getIntegral 每消费 1 元，获N积分
    // maxIntegral 单次消费最高获N积分
    // integralOffset 每使用N积分，抵扣1元
    // conditions 使用条件（订单满N，可用积分）
    // userMaxIntegral 单笔订单最高可用N积分
    if (componentId == 'integralSwitch') {
      if (app.globalData.userAndTenantInfo) {
        startUseIntegral(this, app.globalData.userAndTenantInfo.integral, componentId, checked);
      } else {
        app.userAndTenantInfoCallback = res => {
          startUseIntegral(this, res.integral, componentId, checked);
        }
      }


    }
  },

  chooseStore: function (e) {
    var mode2 = e.currentTarget.dataset.mode;
    if (this.data.orderNO) {
      wx.navigateTo({
        url: '/pages/myself/store/StoreInfo?gototype=1&mode=' + e.currentTarget.dataset.mode + '&pagepath=' + e.currentTarget.dataset.pagepath + '&deliverytime=' + this.data.date + '&orderNO=' + this.data.orderNO + '&orderId=' + this.data.orderId + '&againPay=' + this.data.againPay + '&orderDesc=' + this.data.orderDesc
      })
    } else {
      wx.navigateTo({
        url: '/pages/myself/store/StoreInfo?gototype=1&mode=' + e.currentTarget.dataset.mode + '&pagepath=' + e.currentTarget.dataset.pagepath + '&deliverytime=' + this.data.date
      })
    }

  },

  formIdSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  /**
  * 选择支付方式
  */
  pay: function (e) {
    var data = {};
    data.linkType = 0;
    data.distributorId = this.data.distributorId;
    data.shoppingCartIds = this.data.shoppingCartIds; // 购物车结算时有值
    data.orderId = this.data.orderId; // 修改订单时有值
    data.products = this.data.products;
    data.content = this.data.content;
    data.dateLink = this.data.dateLink;
    data.subscribeDate = utils.formatDate(new Date(this.data.date)) + ':00';
    //data.spellGroupId = "";
    if (this.data.coupon) {
      data.couponId = this.data.coupon.id;
      data.couponPrice = this.data.couponPrice;
    }
    if (this.data.integralRule) {
      data.integralId = this.data.integralRule.id;
      if (this.data.integralPrice > 0) {
        data.integral = this.data.integralRule.userMaxIntegral;
        data.integralPrice = this.data.integralPrice;
      }
    } else {
      data.integralId = null;
    }
    /**
     * type: 0线上
     * type: 1线下
     */
    if (this.data.radiochecked == 1) {
      data.type = 1;
      data.customStoreId = this.data.shop_details.id; //门店id
      if (this.data.shop_details.name) {
        if (this.data.date != '自提时间') {
          if (this.data.discountPrice > 0) {
            // 如果订单号存在，则为修改订单或再次购买，否则创建订单
            if (this.data.orderNO) {
              // againPay为2，则为再次购，需要重新创建订单，否则为修改订单
              if (this.data.againPay == 2) {
                network._post_json(this, api.createOrder, data, success);
              } else {
                network._post_json(this, api.modifyOrder, data, modifySuccess);
              }
            } else {
              network._post_json(this, api.createOrder, data, success);
            }
          } else {
            this.showZanTopTips(this.prompt, '支付金额不能为0');
          }
        } else {
          this.showZanTopTips(this.prompt, '请选择自提日期');
        }

      } else {
        this.showZanTopTips(this.prompt, '请选择自提门店');
      }

    } else {
      if (this.data.deliverAddress) {
        data.userName = this.data.userName;
        data.deliverAddress = this.data.deliverAddress;
        data.userPhone = this.data.userPhone;
        data.type = 0;
        if (this.data.discountPrice > 0) {
          // 如果订单号存在，则为修改订单或再次购买，否则创建订单
          if (this.data.orderNO) {
            // againPay为2，则为再次购，需要重新创建订单，否则为修改订单
            if (this.data.againPay == 2) {
              network._post_json(this, api.createOrder, data, success);
            } else {
              network._post_json(this, api.modifyOrder, data, modifySuccess);
            }
          } else {
            network._post_json(this, api.createOrder, data, success);
          }
        } else {
          this.showZanTopTips(this.prompt, '支付金额不能为0');
        }
      } else {
        this.showZanTopTips(this.prompt, '请选择物流地址');
      }
    }
  },
  radioChange: function (e) {
    var radiotxt = e.detail.value;
    if (radiotxt == "送货上门") {
      this.setData({
        mode1: 0,
        mode2: 1,
        radiochecked: 0
      })
    } else {
      this.setData({
        mode1: 1,
        mode2: 0,
        radiochecked: 1
      })
    }
  },

  /**
   * 刷新地址
   */
  refreshNotification: function () {
    this.setData({
      shop_details: wx.getStorageSync('shop_details')
    })
  }
}))

// 生成订单
var success = function (that, res) {
  if (res.data.data) {
    that.setData({
      orderId: res.data.data.id,
      orderNO: res.data.data.orderNO,
      OrderDesc: res.data.data.orderDesc,
    })
    // if (that.data.selected) { // 微信支付
    /**
    * 获取个人及商家信息
    */
    if (app.globalData.userAndTenantInfo) {
      // 购买
      network._post_json(that, api.wxPay, {
        shoppingCartIds: that.data.shoppingCartIds,
        products: that.data.products,
        appId: app.globalData.appId,
        orderId: res.data.data.orderNO,
        OrderDesc: res.data.data.orderDesc,
        totalFee: res.data.data.total
      }, wxPaySuccess);
    } else {
      app.userAndTenantInfoCallback = res => {
        // 购买
        network._post_json(that, api.wxPay, {
          shoppingCartIds: that.data.shoppingCartIds,
          products: that.data.products,
          appId: app.globalData.appId,
          orderId: res.data.data.orderNO,
          OrderDesc: res.data.data.orderDesc,
          totalFee: res.data.data.total
        }, wxPaySuccess);
      }
    }
  }
}

// 修改订单
var modifySuccess = function (that, res) {
  if (res.data.message == '修改订单成功') {
    if (app.globalData.userAndTenantInfo) {
      // 购买
      network._post_json(that, api.wxPay, {
        shoppingCartIds: that.data.shoppingCartIds,
        products: that.data.products,
        appId: app.globalData.appId,
        orderId: res.data.data.orderNO,
        OrderDesc: res.data.data.orderDesc,
        totalFee: res.data.data.total
      }, wxPaySuccess);
    } else {
      app.userAndTenantInfoCallback = res => {
        // 购买
        network._post_json(that, api.wxPay, {
          shoppingCartIds: that.data.shoppingCartIds,
          products: that.data.products,
          appId: app.globalData.appId,
          orderId: res.data.orderNO,
          OrderDesc: res.data.orderDesc,
          totalFee: res.data.total
        }, wxPaySuccess);
      }
    }
  }
}

// 微信支付结果
var wxPaySuccess = function (that, res) {
  if (res.data.data) {
    wx.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function (res) {
        if (that.data.orderNO) {
          wx.redirectTo({
            url: "/pages/myself/order/OrderDetails?orderId=" + that.data.orderId
          })
        } else {
          wx.navigateTo({
            url: "/pages/myself/order/OrderDetails?orderId=" + that.data.orderId
          })
        }
        //获取页面栈
        // var pages = getCurrentPages();
        // if (pages.length > 1) {
        //   //上一个页面实例对象
        //   var prePage = pages[pages.length - 2];
        //   if (prePage.refresh && typeof (prePage.refresh) == "function") {
        //     prePage.refresh();
        //   }
        // }
        // wx.navigateBack({

        // })
        if (that.data.formId) {
          network._post_json(that, api.sendCoupn, { formId: that.data.formId, type: 3, price: that.data.discountPrice }, sendCoupnSuccess);
        }
      },
      fail: function (res) {
        // wx.navigateTo({
        //   url: "/pages/myself/order/OrderDetails?orderId=" + that.data.orderId
        // })
      },
    });
  }
}

var integralRuleSuccess = function (that, res) {
  // getIntegral 每消费 1 元，获N积分
  // maxIntegral 单次消费最高获N积分
  // integralOffset 每使用N积分，抵扣1元
  // conditions 使用条件（订单满N，可用积分）
  // userMaxIntegral 单笔订单最高可用N积分
  if (res.data.data) {
    var callbackData = res.data.data;
    var jifendikouprice = utils.toDecimal2(callbackData.userMaxIntegral / callbackData.integralOffset)
    that.setData({
      integralRule: callbackData,
      jifendikou: jifendikouprice
    })
  }

}

/**
 * 商品总价
 */
var getTotal = function (that, items) {
  var price = 0;
  for (var i = 0; i < items.length; i++) {
    price += items[i].price * items[i].count
  }
  // that.setData({
  //   allPrice: price
  // })
  return price;
}

/**
 * 去掉数组里重复元素
 */
Array.prototype.unique = function () {
  var res = [];
  var json = {};
  this.sort();
  for (var i = 0; i < this.length; i++) {
    // if (this[i] != 0) {
    //   if (!json[this[i]]) {
    //     res.push(this[i]);
    //     json[this[i]] = 1;
    //   }
    // }
    if (this[i] == 1) {
      if (!json[this[i]]) {
        res.push(this[i]);
        json[this[i]] = 1;
      }
    }
  }
  return res;
}

/**
 * 计算商品实付价格,单位：分
 * price 原价
 * couponPrice 优惠券可抵多少钱
 * integralPrice 积分可抵多少钱
 */
var getPaidPrice = function (that, price, couponPrice, integralPrice) {
  var amount = 0;
  if (price - couponPrice > integralPrice) {
    amount = price - couponPrice - integralPrice;
  } else {
    amount = price - couponPrice
    that.setData({
      integralSwitch: {
        checked: false
      },
    })

  }
  return amount;
}

// 获取个人及商家信息结果
var userAndTenantInfoSuccess = function (that, res) {
  if (res.data.data) {
    var userAndTenantInfo = res.data.data;
    app.globalData.userAndTenantInfo = userAndTenantInfo;
  }
}

var startUseIntegral = function (that, integral, componentId, checked) {
  if (integral >= that.data.integralRule.userMaxIntegral) {
    var jifenprice = that.data.integralRule.userMaxIntegral / that.data.integralRule.integralOffset * 100;
    if (!checked) {
      that.setData({
        integralPrice: 0,
        [`${componentId}.checked`]: false,
        discountPrice: getPaidPrice(that, that.data.allPrice, that.data.couponPrice, 0)
      })
    }
    if (that.data.allPrice >= that.data.integralRule.conditions && that.data.discountPrice > jifenprice) {
      that.setData({
        [`${componentId}.checked`]: checked
      });
      // 这里是使用积分的逻辑代码
      if (checked) {
        var integralPrice = utils.toDecimal2(that.data.integralRule.userMaxIntegral / that.data.integralRule.integralOffset) * 100;
        that.setData({
          integralPrice: integralPrice,
          discountPrice: getPaidPrice(that, that.data.allPrice, that.data.couponPrice, integralPrice)
        })
      } else {
        that.setData({
          integralPrice: 0,
          [`${componentId}.checked`]: false,
          discountPrice: getPaidPrice(that, that.data.allPrice, that.data.couponPrice, 0)
        })
      }
    } else {
      that.showZanTopTips(this.prompt, '当前支付金额不满足积分使用条件');
      that.setData({
        [`${componentId}.checked`]: false
      });
    }
  } else {
    that.showZanTopTips(this.prompt, '积分不足');
    that.setData({
      [`${componentId}.checked`]: false
    });
  }
}

var getCount = function (that, products) {
  let count = 0;
  for (let i = 0; i < products.length; i++) {
    count += products[i].count;
  }
  that.setData({
    count: count
  })
}

var sendCoupnSuccess = function (that, res) { }